import dayjs from 'dayjs';
import type { Directive, DirectiveHook } from 'vue';

type FormatValue = {
  dateTime?: number;
  template?: string;
  type?: 'uts' | 'mts';
};

const _formatValue = (el: Element, value: FormatValue) => {
  const { dateTime, template, type }: FormatValue = {
    ...{ dateTime: 0, template: 'YYYY-MM-DD HH:mm:ss', type: 'uts' },
    ...value
  };

  if (!dateTime || String(dateTime) === String(0)) {
    el.textContent = '-';
    return;
  }
  const val = type === 'uts' ? dateTime * 1000 : dateTime;
  el.textContent = dayjs(val).format(template || 'YYYY-MM-DD HH:mm:ss');
};
const formatValue: DirectiveHook = (el, binding) => {
  // binding: {dateTime: 1679584806228, template: 'YYYY-MM-DD HH:mm:ss', type: 'mts' | 'uts' }
  // format Docs: https://day.js.org/docs/en/display/format
  _formatValue(el, binding.value);
};

const formatMTS: DirectiveHook = (el, binding) => {
  // binding: 1679584806228
  _formatValue(el, {
    dateTime: Number(binding.value ?? 0),
    type: 'mts'
  });
};
const formatUTS: DirectiveHook = (el, binding) => {
  // binding: 1679584806228
  _formatValue(el, {
    dateTime: Number(binding.value ?? 0)
  });
};

export const uts: Directive = {
  mounted: formatUTS,
  updated: formatUTS
};

export const mts: Directive = {
  mounted: formatMTS,
  updated: formatMTS
};

export const formatUnixHandler: Directive = {
  mounted: formatValue,
  updated: formatValue
};
